﻿using SharpGL.SceneGraph.Assets;

namespace SharpGL.SceneGraph.Helpers
{
    internal class FreezableHelper
    {
        #region Private Fields

        /// <summary>
        /// The display list internally.
        /// </summary>
        private DisplayList displayList = null;

        #endregion Private Fields

        #region Public Methods

        /// <summary>
        /// Freezes the specified instance.
        /// </summary>
        /// <param name="gl">The currentOpenGLContext instance.</param>
        /// <param name="renderable">The renderable.</param>
        public void Freeze(OpenGL gl, IRenderable renderable)
        {
            //  Handle the trivial case.
            if (IsFrozen)
                return;

            //  Create the display list.
            DisplayList displayList = new DisplayList();
            displayList.Create(gl);

            //  Start the display list.
            displayList.Begin(DisplayList.DisplayListMode.Compile);

            //  Render the object.
            renderable.Render(gl, RenderMode.Design);

            //  End the display list.
            displayList.End();

            this.displayList = displayList;
        }

        /// <summary>
        /// Renders the specified currentOpenGLContext.
        /// </summary>
        public void Render()
        {
            if (IsFrozen)
                displayList.Call();
        }

        /// <summary>
        /// Unfreezes the specified currentOpenGLContext.
        /// </summary>
        public void Unfreeze()
        {
            if (IsFrozen)
            {
                displayList.Destroy();
                displayList = null;
            }
        }

        #endregion Public Methods

        #region Public Properties

        /// <summary>
        /// Gets a value indicating whether this instance is frozen.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is frozen; otherwise, <c>false</c>.
        /// </value>
        public bool IsFrozen
        {
            get { return (this.displayList != null); }
        }

        #endregion Public Properties
    }
}
